package com.iwhalecloud.bss.kite.cucc.service.shoppingcart.query;

import com.iwhalecloud.bss.kite.client.api.shoppingcart.query.IQueryShoppingCartGroupInstService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.dto.shoppingcart.ShoppingCartGroupInstAttrDTO;
import com.iwhalecloud.bss.kite.client.dto.shoppingcart.ShoppingCartGroupInstDTO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.TransactionUtils;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteShoppingCartGroupInst;
import com.iwhalecloud.bss.kite.dataservice.entity.KiteShoppingCartGroupInstAttr;
import com.iwhalecloud.bss.kite.dataservice.mapper.shoppingcart.ShoppingCartGroupInstAttrMapper;
import com.iwhalecloud.bss.kite.service.shoppingcart.cache.ShoppingCartGroupCache;
import com.iwhalecloud.bss.kite.service.shoppingcart.operate.OperateShoppingCartService;
import com.ztesoft.bss.common.bo.SimpleLoginInfo;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

@Service
public class QueryShoppingCartGroupInstService implements IQueryShoppingCartGroupInstService {

    private final ZLogger logger = ZLoggerFactory.getLogger(getClass(), KeyConsts.LOG_MODULE);

    @Resource
    private QueryShoppingCartService queryShoppingCartService;

    @Resource
    private OperateShoppingCartService operateShoppingCartService;

    @Resource
    private ShoppingCartGroupInstAttrMapper shoppingCartGroupInstAttrMapper;

    @Override
    public int countShoppingCartGroupInsts(String userId, String lanId, String custId, int time) {
        List<ShoppingCartGroupInstDTO> groupInstDTOs = new ArrayList<>();
        try {
            SimpleLoginInfo simpleLoginInfo = queryShoppingCartService.getSimpleLoginInfo(userId, lanId);
            // 获取数据库购物车分组
            List<KiteShoppingCartGroupInst> groupInsts = queryShoppingCartService
                .selectShoppingCartGroupInsts(simpleLoginInfo, userId, custId);
            for (KiteShoppingCartGroupInst groupInst : groupInsts) {
                // 如果是待录入，缓存数据不存在（超过有效时间）则删除表中的数据，不返回前端展示
                if (KeyConsts.SHOPPING_CART_GROUP_STATUS_INPUT.equals(groupInst.getStatusCd())) {
                    ShoppingCartGroupInstDTO cacheGroupInstDTO = ShoppingCartGroupCache.getGroupInstDto(userId, custId,
                        groupInst.getGroupId());
                    if (Objects.isNull(cacheGroupInstDTO)) {
                        TransactionUtils.executeNew(() -> {
                            operateShoppingCartService.deleteShoppingCartGroupInfo(groupInst.getGroupId(), custId,
                                userId, Boolean.TRUE);
                        });
                        continue;
                    }
                }
                DataResult<ShoppingCartGroupInstDTO> dataResult = operateShoppingCartService
                    .createSimpleShoppingCartGroupInstInfo(simpleLoginInfo, groupInst.getGroupId(),
                        groupInst.getStatusCd(), groupInst.getCreateStaff(), custId);
                ShoppingCartGroupInstDTO groupInstDTO = Optional.ofNullable(dataResult).map(DataResult::getResultObject)
                    .orElse(null);
                if (Objects.nonNull(groupInstDTO)) {
                    groupInstDTOs.add(groupInstDTO);
                }
            }
        }
        catch (Exception e) {
            logger.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), e, e.getMessage());
            try {
                if (time == 0) {
                    return countShoppingCartGroupInsts(userId, lanId, custId, time + 1);
                }
            }
            catch (Exception ex) {
                logger.error(ErrorConsts.SYSTEM_ERROR.getErrorCode(), ex, ex.getMessage());
            }
        }

        return groupInstDTOs.size();
    }

    @Override
    public List<ShoppingCartGroupInstAttrDTO> listShoppingCartGroupInstAttrs(String groupId, String custId) {
        Example example = new Example(KiteShoppingCartGroupInstAttr.class);
        example.createCriteria().andEqualTo("groupId", groupId).andEqualTo("custId", custId);
        List<KiteShoppingCartGroupInstAttr> groupInstAttrs = shoppingCartGroupInstAttrMapper.selectByExample(example);
        if (KiteObjectUtils.isEmpty(groupInstAttrs)) {
            groupInstAttrs = shoppingCartGroupInstAttrMapper.selectGroupInstAttrsFromHis(groupId, custId, null);
        }
        return KiteBeanUtils.copyPropsForList(groupInstAttrs, ShoppingCartGroupInstAttrDTO.class);
    }
}
